/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.asportoonline.integration;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.asportoonline.entities.Cliente;
import org.asportoonline.entities.Indirizzo;
import org.asportoonline.entities.Locale;

/**
 *
 * @author fe
 */
@Stateless
public class LocaleFacadeImplementation extends AbstractFacade<Locale> implements LocaleFacade {
    @PersistenceContext(unitName = "AsportoOnline-ejbPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public LocaleFacadeImplementation() {
        super(Locale.class);
    }

    @Override
    public Locale find(long id) {
        Query query = em.createQuery("select l from Locale l where l.idLocale = :idlocale");
        query.setParameter("idlocale", id);
        List<Locale> ll = (List<Locale>)query.getResultList();
        if(ll==null || ll.isEmpty())    return null;
        return (Locale)ll.get(0);
    }

    public Locale find(String nome) {
        Query query = em.createQuery("select l from Locale l where l.nome = :nome");
        query.setParameter("nome", nome);
        List<Locale> ll = (List<Locale>)query.getResultList();
        if(ll==null || ll.isEmpty())    return null;
        return (Locale)ll.get(0);
    }
    
    public List<Locale> fetch_vendor_locals(Cliente c) {
        Query query = em.createQuery("select l from Locale l where l.proprietario = :prop");
        query.setParameter("prop", c);
        List<Locale> ll = (List<Locale>)query.getResultList();
        
        if(ll==null || ll.isEmpty()) return null;        
        else  return ll;
    }
  
    @Override
    public void edit(Locale l) {
        em.merge(l);
    }
    
    public List<String> fetch_all_locality() {
        Query query = em.createQuery("select distinct l.indirizzo.citta from Locale l order by l.indirizzo.citta");
        List<String> lc = (List<String>)query.getResultList();
        
        if(lc==null || lc.isEmpty()) {
            return null;            
        }
        
        return lc;
    }    
    
    public List<Locale> find_for_locality(String locality) {
        Query query = em.createQuery("select l from Locale l where l.indirizzo.citta = :loc");
        query.setParameter("loc", locality);
        List<Locale> ll = (List<Locale>)query.getResultList();
        return ll;
    }
}
